package com.ly.config;

import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * @author ：LY
 * @date ：Created in 2020/11/7 16:19
 * @modified By：
 */
@Configuration
@EnableJpaRepositories(basePackages = "com.ly.repository")
@EnableTransactionManagement
public class JPAConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource(){
        //获取数据源 通过ConfigurationProperties将配置文件的连接信息注入到DataSource中
        return DataSourceBuilder.create().build();
    }

    /**
     * 实体类管理器
     * @return
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){

        // 创建Hibernate实例
        HibernateJpaVendorAdapter jpaVendor = new HibernateJpaVendorAdapter();
        //是否生成sql,设置成false
        jpaVendor.setGenerateDdl(false);
        //设置实体映射管理工厂类
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        //设置属性
        entityManagerFactoryBean.setDataSource(dataSource());
        //设置JPA适配器
        entityManagerFactoryBean.setJpaVendorAdapter(jpaVendor );
        //设置实体类包名
        entityManagerFactoryBean.setPackagesToScan("com.ly.entity");
        return  entityManagerFactoryBean;
    }

    /**
     * 事务管理类
     * @param entityManagerFactory
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory){
        JpaTransactionManager transactionManager= new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }
}
